<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket弹幕测试</title>
    <style>
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        #danmakuContainer {
            width: 800px;
            height: 450px;
            border: 2px solid #333;
            position: relative;
            overflow: hidden;
            background: #000;
            margin: 10px 0;
            border-radius: 8px;
        }
        .danmaku {
            position: absolute;
            white-space: nowrap;
            font-size: 20px;
            font-weight: bold;
            text-shadow: 1px 1px 2px #000;
            font-family: "Microsoft YaHei", sans-serif;
        }
        .controls {
            margin: 15px 0;
            padding: 10px;
            background: white;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        input, select, button {
            padding: 8px 12px;
            margin: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background: #0056b3;
        }
        #status {
            padding: 10px;
            background: #e9ecef;
            border-radius: 4px;
            margin: 10px 0;
        }
        h1 {
            color: #333;
            text-align: center;
        }
    </style>
</head>
<body>
<h1>WebSocket弹幕测试</h1>

<div class="controls">
    <strong>房间控制：</strong>
    <input type="text" id="videoId" placeholder="视频ID" value="test-video-001">
    <button onclick="joinRoom()">加入房间</button>
    <button onclick="leaveRoom()">离开房间</button>
</div>

<div class="controls">
    <strong>弹幕发送：</strong>
    <input type="text" id="messageInput" placeholder="输入弹幕内容" style="width: 300px;">
    <input type="color" id="colorPicker" value="#ff0000">
    <select id="positionSelect">
        <option value="fly">滚动弹幕</option>
        <option value="top">顶部弹幕</option>
        <option value="bottom">底部弹幕</option>
    </select>
    <button onclick="sendDanmaku()">发送弹幕</button>
</div>

<div id="danmakuContainer"></div>

<div id="status">状态: 未连接</div>

<script>
    // 修复乱码：确保使用UTF-8编码
    let websocket = null;
    const danmakuContainer = document.getElementById('danmakuContainer');
    const statusDiv = document.getElementById('status');

    // 连接WebSocket
    function connectWebSocket() {
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const wsUrl = `${protocol}//${window.location.host}/websocket/danmaku`;

        console.log('尝试连接到:', wsUrl);

        websocket = new WebSocket(wsUrl);

        websocket.onopen = function(event) {
            statusDiv.textContent = '状态: 已连接';
            statusDiv.style.color = 'green';
            console.log('WebSocket连接已建立');

            // 自动加入默认房间
            joinRoom();
        };

        websocket.onmessage = function(event) {
            try {
                const message = JSON.parse(event.data);
                console.log('收到消息:', message);
                handleWebSocketMessage(message);
            } catch (e) {
                console.error('消息解析错误:', e);
            }
        };

        websocket.onclose = function(event) {
            statusDiv.textContent = '状态: 连接关闭';
            statusDiv.style.color = 'red';
            console.log('WebSocket连接已关闭');
        };

        websocket.onerror = function(error) {
            statusDiv.textContent = '状态: 连接错误';
            statusDiv.style.color = 'red';
            console.error('WebSocket错误:', error);
        };
    }

    // 处理WebSocket消息
    function handleWebSocketMessage(message) {
        switch(message.type) {
            case 'system':
                showSystemMessage(message.message);
                break;
            case 'join_success':
                showSystemMessage('成功加入房间: ' + message.videoId);
                break;
            case 'danmaku':
                displayDanmaku(message);
                break;
            case 'error':
                showSystemMessage('错误: ' + message.message);
                break;
            default:
                console.log('未知消息类型:', message.type);
        }
    }

    // 显示系统消息
    function showSystemMessage(msg) {
        const systemMsg = document.createElement('div');
        systemMsg.style.cssText = `
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                color: yellow;
                font-size: 24px;
                text-shadow: 2px 2px 4px #000;
                z-index: 1000;
            `;
        systemMsg.textContent = msg;
        danmakuContainer.appendChild(systemMsg);

        setTimeout(() => {
            if (systemMsg.parentNode) {
                systemMsg.parentNode.removeChild(systemMsg);
            }
        }, 2000);
    }

    // 显示弹幕
    function displayDanmaku(danmaku) {
        const danmakuElement = document.createElement('div');
        danmakuElement.className = 'danmaku';
        danmakuElement.textContent = danmaku.content;
        danmakuElement.style.color = danmaku.color || '#ffffff';

        const containerHeight = danmakuContainer.clientHeight;
        const containerWidth = danmakuContainer.clientWidth;

        switch(danmaku.position) {
            case 'top':
                danmakuElement.style.top = '10px';
                danmakuElement.style.left = '50%';
                danmakuElement.style.transform = 'translateX(-50%)';
                break;
            case 'bottom':
                danmakuElement.style.top = (containerHeight - 30) + 'px';
                danmakuElement.style.left = '50%';
                danmakuElement.style.transform = 'translateX(-50%)';
                break;
            case 'fly':
            default:
                const top = Math.random() * (containerHeight - 30);
                danmakuElement.style.top = top + 'px';
                danmakuElement.style.left = containerWidth + 'px';
                break;
        }

        danmakuContainer.appendChild(danmakuElement);

        // 弹幕动画
        if (danmaku.position === 'fly') {
            const duration = 8; // 秒
            const distance = containerWidth + danmakuElement.offsetWidth;

            danmakuElement.style.transition = `transform ${duration}s linear`;

            // 触发动画
            setTimeout(() => {
                danmakuElement.style.transform = `translateX(-${distance}px)`;
            }, 100);

            // 动画结束后移除元素
            setTimeout(() => {
                if (danmakuElement.parentNode) {
                    danmakuElement.parentNode.removeChild(danmakuElement);
                }
            }, duration * 1000);
        } else {
            // 静态弹幕，3秒后消失
            setTimeout(() => {
                if (danmakuElement.parentNode) {
                    danmakuElement.parentNode.removeChild(danmakuElement);
                }
            }, 3000);
        }
    }

    // 加入房间
    function joinRoom() {
        if (!websocket || websocket.readyState !== WebSocket.OPEN) {
            showSystemMessage('请先建立WebSocket连接');
            return;
        }

        const videoId = document.getElementById('videoId').value;
        const message = {
            type: 'join',
            videoId: videoId
        };
        websocket.send(JSON.stringify(message));
    }

    // 离开房间
    function leaveRoom() {
        if (!websocket || websocket.readyState !== WebSocket.OPEN) {
            return;
        }

        const videoId = document.getElementById('videoId').value;
        const message = {
            type: 'leave',
            videoId: videoId
        };
        websocket.send(JSON.stringify(message));
        showSystemMessage('已离开房间: ' + videoId);
    }

    // 发送弹幕
    function sendDanmaku() {
        if (!websocket || websocket.readyState !== WebSocket.OPEN) {
            showSystemMessage('请先建立WebSocket连接');
            return;
        }

        const content = document.getElementById('messageInput').value;
        const color = document.getElementById('colorPicker').value;
        const position = document.getElementById('positionSelect').value;
        const videoId = document.getElementById('videoId').value;

        if (!content.trim()) {
            showSystemMessage('请输入弹幕内容');
            return;
        }

        const message = {
            type: 'danmaku',
            videoId: videoId,
            content: content,
            color: color,
            position: position
        };

        websocket.send(JSON.stringify(message));
        document.getElementById('messageInput').value = '';
    }

    // 键盘事件支持
    document.getElementById('messageInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendDanmaku();
        }
    });

    // 页面加载时自动连接
    window.onload = function() {
        connectWebSocket();
    };

    // 页面关闭时断开连接
    window.addEventListener('beforeunload', function() {
        if (websocket) {
            websocket.close();
        }
    });
</script>
</body>
</html>